<?php
declare (strict_types=1);

namespace app\middleware;


use app\model\coach\UserCoachModel;
use app\model\user\UserModel;
use app\Request;

class CoachAuth
{

    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request, \Closure $next)
    {
        try {
            $token = $request->header('Authorization');
            if (empty($token)) {
                throw new \Exception('请登录后重试');
            }
            $userInfo = UserCoachModel::getByToken($token);
            if (empty($userInfo)) {
                throw new \Exception('请重新登录');
            }
//            if ($userInfo['token_valid_time'] <= time()) {
//                throw new \Exception('请重新登录');
//            }
            $request->withMiddleware(['userId' => $userInfo['id']]);
            $request->withMiddleware(['userInfo' => $userInfo]);
        } catch (\Exception $exception) {
            return json()->data(['code' => -1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}
